(function(window) {
    let that = null;
    class Title {
        constructor() {
            this.game = new Game(); //获取游戏控制器
            this.mode = [`正常模式(吃到自己会死掉)`, `无限模式(吃到自己不会死)`, `操作方法：上下左右键控制蛇蛇方向，空格键加速，Esc暂停`];
            this.modeFlag = 0;
            this.tip = null;
            that = this;
        }
        render = function() {
            let h1 = document.createElement('h1');
            h1.innerHTML = '贪吃蛇';
            document.body.appendChild(h1);
            let sec = document.createElement('section');
            document.body.appendChild(sec);
            let ul = document.createElement('ul');
            sec.appendChild(ul);
            let li = this.addLi(ul, '开始游戏');
            li.addEventListener('mousedown', startGame);
            this.tip = document.createElement('p');
            this.showTip(li, this.mode, 1);
            li = this.addLi(ul, '切换模式');
            li.addEventListener('mousedown', changeMode);
            this.showTip(li, this.mode, 2);
            li = this.addLi(ul, '退出游戏');
            this.showTip(li, `离开页面`, 3);
            li.addEventListener('mouseup', leftGame);
            document.addEventListener('keyup', function() {
                if (arguments[0].key === 'Enter') {
                    startGame();
                }
            })
        }
        addLi = function(ul, inText) {
            let li = document.createElement('li');
            li.innerHTML = inText;
            ul.appendChild(li);
            return li;
        }
        showTip = function(li, inText, n) {
            this.tip.className = 'tips';
            document.body.appendChild(this.tip);
            li.addEventListener('mouseover', function() {
                if (n === 1) { this.tip.innerHTML = inText[2]; } else if (n === 3) {
                    this.tip.innerHTML = '离开页面';
                } else {
                    this.tip.innerHTML = inText[this.modeFlag];
                }
                this.tip.style.display = 'block';
            }.bind(this))
            li.addEventListener('mouseleave', function() {
                this.tip.style.display = 'none';
            }.bind(this))
        }
    }

    function startGame() {
        // 初始化控制器
        that.game.initial(that.modeFlag);
        // 游戏开始
        that.game.start();
    }

    function leftGame() {
        if (confirm(`确认离开游戏吗？`))
            window.close();
    }

    function changeMode() {
        that.modeFlag = Number(!that.modeFlag);
        that.tip.innerHTML = `${that.mode[that.modeFlag]}`;
    }
    window.Title = Title;
}(window))